/**
  * Created by Joshua Conero(O'Uymas) on 2017/1/14 0014.
  * QQ: 957376074
  * E-mail: Brximl@163.com
  * 数据执行库
  */
package conero.sql
import java.sql.{Connection, ResultSet}
import scala.collection.mutable.ArrayBuffer
class Execute(con:Connection) extends DBase{
  private var executeSql = ""
  val db = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
  // 全部数据结果集获取
  def select(sql:String=""):Array[Map[String,String]] = {
    executeSql = if(sql != "") sql else executeSql
    val result = db.executeQuery(executeSql)
    val dt = result.getMetaData
    // 遍历结果
    val len = dt.getColumnCount
    var retArr = new ArrayBuffer[Map[String,String]]
    while(result.next()){
      var values = Map[String,String]()
      for(i<- 1 to len){
        print(result.getString(i))
        if(i != len) print(",")
        values += (dt.getColumnLabel(i) -> result.getString(i))
      }
      retArr += values
    }
    retArr.toArray
  }
  // 单列数组获取某值
  def get(key:String="",sql:String=""):String = {
    executeSql = if(sql != "") sql else executeSql
    if(executeSql == "") return ""
    val result = db.executeQuery(executeSql)
    result.next()
    if(key != "")
      result.getString(key)
    else
      result.getString(1)
  }
  // 获取单列
  def find(sql:String=""):Map[String,String] = {
    val result = db.executeQuery(sql)
    val dt = result.getMetaData
    result.next()
    val len = dt.getColumnCount
    var retArr = Map[String,String]()
    for(i<- 1 to len){
      retArr += ( dt.getColumnLabel(i) -> result.getString(i))
    }
    retArr
  }
  // 更新/删除操作
  def update(sql:String=""):Int = {
    executeSql = if(sql != "") sql else executeSql
    if(executeSql == "") return 0
    db.executeUpdate(sql)
  }
  // 设置执行SQL
  def setSQL(sql:String):this.type ={
    executeSql = sql
    this
  }
}
